<script setup>
import { ref, onMounted, reactive } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import { Eleme } from '@element-plus/icons-vue'
import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
dayjs.extend(utc)
dayjs.extend(duration)

let electron = null
if (window.electron) {
  electron = window.electron
}
// 不上榜数据列表
let columns = ref([])
let tableData = ref([])
let loading = ref(false)
let loading2 = ref(false)
let TotalData = ref(false)

// 缓存总数据
let TokenListData = ref([])

// 表单查询
let formInline = reactive({
  nickName: '',
  user_id_str: '',
  // updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})
// 表单提交
const onSubmit = async () => {
  console.log('submit!', formInline)
  await HuoShanTokenList()
}
// 检测账号失败的结果
let failAccount = ref([])
// 检测账号成功的结果
let sucAccount = ref([])
// 检测账号失败的结果弹框
let dialogVisible = ref(false)

async function exporAccount(type) {
  let nowtime = dayjs().format('MM.DD')
  let str = ``
  if (type == 1) {
    if (sucAccount.value.length == 0) {
      ElMessage({
        type: 'error',
        message: '请先检测账号!'
      })
      return
    }
    sucAccount.value.forEach((item) => {
      str += `${item}`
      str += '\r\n'
    })
  }
  if (type == 2) {
    if (failAccount.value.length == 0) {
      ElMessage({
        type: 'error',
        message: '请先检测账号!'
      })
      return
    }
    failAccount.value.forEach((item) => {
      str += `${item}`
      str += '\r\n'
    })
  }

  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
  let link = document.createElement('a')
  link.href = uri
  if (type == 1) {
    link.download = `${nowtime}x${sucAccount.value.length}` + '.txt'
  }
  if (type == 2) {
    link.download = `${nowtime}无效x${failAccount.value.length}` + '.txt'
  }
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

async function CheckAccountStatus(item) {
  console.warn('CheckAccountStatus', item)
  if (tableData.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '没有可用的账号数据!'
    })
    return
  }
  if (item == 'batch') {
    failAccount.value = []
    sucAccount.value = []
    loading2.value = true
    let pro_tmp = []
    for (let index = 0; index < TokenListData.value.length; index++) {
      const element = TokenListData.value[index]
      pro_tmp.push(getTokenInfo(element.x_tt_token, false))
    }
    await Promise.all(pro_tmp)
    // let results = await Promise.all(pro_tmp)
    // let success = results.filter((item) => item === true)
    // let fail = results.filter((item) => item === false)
    loading2.value = false
    dialogVisible.value = true
    ElMessage({
      type: 'success',
      message: '批量检测账号状态成功!'
    })
    return
  }
  let result = await getTokenInfo(item.x_tt_token, true)
  if (result) {
    ElMessage({
      type: 'success',
      message: '检测账号状态成功!'
    })
  }
}

//根据token 获取用户详细信息
async function getTokenInfo(token, flag_) {
  try {
    let url = 'https://aweme.snssdk.com/aweme/v1/user/profile/self/?aid=1128'
    //时间戳毫秒
    let _rticket = new Date().getTime()
    //时间戳秒
    let ts = parseInt(_rticket / 1000)
    const response_ = await fetch(url, {
      method: 'GET',
      headers: {
        url: url,
        'X-Khronos': ts + '',
        'sdk-version': '1',
        'X-SS-REQ-TICKET': _rticket + '',
        'User-Agent': 'ttnet okhttp/3.10.0.1',
        Host: 'aweme.snssdk.com',
        Connection: 'Keep-Alive',
        'x-tt-token': token
      },
      body: undefined
    })
    let response = await response_.json()
    if (response && response.status_code != 0) {
      failAccount.value.push(token)
      if (flag_) {
        ElMessage({
          type: 'error',
          message: response.status_msg || '账号无效'
        })
      }
      return false
    }
    sucAccount.value.push(token)
    return true
  } catch (error) {
    failAccount.value.push(token)
    return false
  }
}

columns.value.push(
  ...[
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'id',
      label: '用户Id'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'x_tt_token',
      label: '用户x_tt_token'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'token',
      label: 'token'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'status',
      label: '状态'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'createdAt',
      label: '创建时间'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'operate',
      label: '操作'
    }
  ]
)

onMounted(async () => {
  let TokenList = localStorage.getItem('TokenList')
  if (TokenList) {
    TokenList = JSON.parse(TokenList)
    tableData.value = TokenList.slice(0, 50)
    TotalData.value = TokenList.length
    TokenListData.value = TokenList || []
  }

  if (electron) {
    electron.ipcRenderer.on('TokenList', function (event, arg) {
      console.warn(arg)
      tableData.value = arg.slice(0, 50)
      TotalData.value = arg.length
      localStorage.setItem('TokenList', JSON.stringify(arg))
      TokenListData.value = arg || []
      if (arg) {
        let tmp = arg.map((v) => {
          return v.x_tt_token
        })
        tmp = [...new Set(tmp)]
        ElMessage({
          type: 'success',
          message: `账号导入成功! 总数据:${arg.length} 有效数据:${tmp.length} 重复数据:${
            arg.length - tmp.length
          }`
        })
      }
    })
    // 全参设备导入
    electron.ipcRenderer.on('allParameter', function (event, arg) {
      console.warn(arg)
      localStorage.setItem('allParameter', JSON.stringify(arg))
      if (arg) {
        let tmp = arg.map((v) => {
          return v.x_tt_token
        })
        tmp = [...new Set(tmp)]
        ElMessage({
          type: 'success',
          message: `账号导入成功! 总数据:${arg.length} 有效数据:${tmp.length} 重复数据:${
            arg.length - tmp.length
          }`
        })
      }
    })
  }
})

/**
 *
 * @returns 选择文件解析txt
 *
 */
async function ImportTokenList() {
  if (electron) {
    electron.ipcRenderer.send('ParseFile', true)
  }
}

/**
 *
 * @returns 设备全参选择文件解析txt
 *
 */
async function ImportallParameter() {
  if (electron) {
    electron.ipcRenderer.send('allParameter', true)
  }
}
async function TokenDelete(index) {
  tableData.value.splice(index, 1)
  localStorage.setItem('TokenList', JSON.stringify(tableData.value))
}
async function TokenCleanUp() {
  tableData.value = []
  TotalData.value = 0
  failAccount.value = []
  sucAccount.value = []
  localStorage.removeItem('TokenList')
}

/**
 *
 * 打乱顺序
 *
 */
// function getRandomElements(arr, n) {
//   let tmpArr = JSON.parse(JSON.stringify(arr))
//   let result = new Array(n),
//     len = tmpArr.length,
//     taken = new Array(len)
//   if (n > len) throw new RangeError('getRandomElements: input array is not long enough.')
//   while (n--) {
//     var x = Math.floor(Math.random() * len)
//     result[n] = tmpArr[x in taken ? taken[x] : x]
//     taken[x] = --len in taken ? taken[len] : len
//   }
//   return result
// }
</script>

<template>
  <div class="container no-drag">
    <div class="search">
      <el-form ref="queryForm" :inline="true" :model="formInline">
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            :loading-icon="Eleme"
            :loading="loading2"
            @click="CheckAccountStatus('batch')"
            >批量检测账号状态</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary">有效账号数{{ sucAccount.length }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="danger">无效账号数{{ failAccount.length }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="exporAccount(1)">导出有效账号数</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="danger" @click="exporAccount(2)">导出无效账号数</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      stripe
      row-key="id"
      size="large"
      style="width: 100%"
      height="500"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      >
        <template #default="scope">
          <div v-if="item.prop == 'operate'">
            <el-button size="small" type="primary" @click="CheckAccountStatus(scope.row)"
              >检测账号状态</el-button
            >
            <el-button size="small" type="danger" @click="TokenDelete(scope.$index)"
              >删除账号</el-button
            >
          </div>
          <div v-else>
            {{ scope.row[item.prop] }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总账号数：{{ TotalData || '0' }} </span>
      <span style="margin-left: 10px">当页账号数：{{ tableData.length || '0' }} </span>
    </div>
    <el-button type="primary" size="small" @click="ImportTokenList">导入账号列表</el-button>
    <el-button type="primary" size="small" @click="ImportallParameter"
      >全参数导入账号列表</el-button
    >
    <el-button size="small" type="danger" @click="TokenCleanUp">清除账号</el-button>

    <!-- 账号批量检测结果 -->
    <el-dialog v-model="dialogVisible" title="批量检测结果" class="no-drag">
      <div style="color: #f56c6c" class="no-drag">无效账号: {{ failAccount.length }}</div>
      <div class="dialogbody no-drag" style="overflow: auto; height: 100%">
        <div v-for="(item, index) in failAccount" :key="index" style="margin-top: 10px">
          <div style="color: #f56c6c; word-wrap: break-word; width: 100%">
            {{ item }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="less">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
